package network;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class FileServer extends JFrame implements Runnable{
	
	ServerSocket server = null;
	Socket socket = null;
	String folder = "/download/";
	static int staticPort = 5555;
	ObjectOutputStream send;

	private JPanel contentPane;
	private JLabel status;
	private JButton btnNewButton;
	private JButton btnServeropen;
	private JScrollPane scrollPane;
	private JTextArea result;



	public FileServer(ObjectOutputStream o) {
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 575, 215);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		contentPane.add(getStatus());
		contentPane.add(getBtnNewButton());
		contentPane.add(getBtnServeropen());
		contentPane.add(getScrollPane());
		this.send=o;
		
		
		try{
			InetAddress ia = InetAddress.getLocalHost(); // 주소를 가져와 타이틀을 IP주소로 변경해준다.			
			setTitle("IP Address: " + ia.getHostAddress() + ", Port Number : " + (staticPort+5));
			
			File f = new File(folder);
			if(!f.exists()){
				f.mkdirs();
			}
			
			staticPort += 5;

		}catch(Exception ei){
			ei.printStackTrace();
		}
	}

	@Override
	public void run() {

		try{
			result.append("서버가 시작되었습니다.\n");
			server = new ServerSocket(staticPort);
			
			InetAddress ia = InetAddress.getLocalHost();
			String ipadd = ia.getHostAddress();
			
			ipadd +="," + staticPort;
			
			//클라이언트에게 IP와 포트번호를 전송
			SocketData sd = new SocketData("fileTransPort",	"server", "서버가 열렸습니다."+ipadd, ipadd);
			send.writeObject(sd);
			send.flush();
			
			result.append("클라이언트 접속 대기중\n");
			socket = server.accept();
			result.append("접속됨\n");

			DataInputStream dis = new DataInputStream(socket.getInputStream());

			String fileName = dis.readUTF();
			result.append("수신된 파일명은 : " + fileName + " 입니다.\n");

			int pos = fileName.lastIndexOf("\\");
			String tempFile = fileName.substring(pos+1);
			result.append("저장될 파일명은 : " + folder + tempFile + "입니다.\n");


			

			FileOutputStream fos = new FileOutputStream(folder + tempFile);
			byte[] b = new byte[1024];
			int n = 0; // 실제로 수신된 바이트의 길이.
			long fileSize=0;
			while((n = dis.read(b)) != -1){
				fos.write(b,0,n);
				fileSize +=n;
			}

			fos.close();
			dis.close();
			socket.close();		
			status.setText("파일 전송 완료! 전송된 파일 크기 : " + fileSize + "bytes");
			//server.close();


		}catch(Exception ex){
			ex.printStackTrace();
		}

	}

	public void svOpen(){
		Thread t = new Thread(this);
		t.start();

	}

	private JLabel getStatus() {
		if (status == null) {
			status = new JLabel("New label");
			status.setBounds(12, 10, 271, 15);
		}
		return status;
	}
	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			btnNewButton = new JButton("Open Folder");
			btnNewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {

				}
			});
			btnNewButton.setBounds(295, 6, 120, 23);
		}
		return btnNewButton;
	}


	private JButton getBtnServeropen() {
		if (btnServeropen == null) {
			btnServeropen = new JButton("ServerOpen");
			btnServeropen.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					svOpen();

				}
			});
			btnServeropen.setBounds(427, 6, 120, 23);
		}
		return btnServeropen;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setBounds(12, 44, 537, 120);
			scrollPane.setViewportView(getResult());
		}
		return scrollPane;
	}
	private JTextArea getResult() {
		if (result == null) {
			result = new JTextArea();
		}
		return result;
	}
}
